package com.jdew.thkj.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.alibaba.fastjson.JSONObject;
import com.jdew.thkj.R;
import com.jdew.thkj.activity.LoginActivity;
import com.jdew.thkj.activity.MainActivity;
import com.jdew.thkj.activity.TbProductDetailActivity;
import com.jdew.thkj.adapter.SuperSearchAdapter;
import com.jdew.thkj.base.BaseFragment;
import com.jdew.thkj.bean.SuperSearchBean;
import com.jdew.thkj.listener.AppBarStateChangeListener;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.onitemInterface.OnItemClickListener;
import com.jdew.thkj.utils.DeviceUtils;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangyang on 2017/11/20.
 */

public class Fragment2 extends BaseFragment {
    @Bind(R.id.swipe_target)
    RecyclerView recycleView;
    @Bind(R.id.appbar)
    AppBarLayout appbar;
    @Bind(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.main_rgp)
    RadioGroup rgp;
    private SuperSearchAdapter adapter;
    private List<SuperSearchBean.DataBean.TbkDgMaterialOptionalResponseBean.ResultListBean.MapDataBean> list;
    private int page = 1;
    private boolean isLoading = false;
    private String sortType = "total_sales_des";

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_leimu;
    }

    @Override
    protected void onCreateViewT() {
        sp = getActivity().getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        RadioButton rb = (RadioButton) rgp.getChildAt(0);
        rb.setChecked(true);
        list = new ArrayList<>();
        adapter = new SuperSearchAdapter(getActivity(), list);
        RequestData();
        setRcycleview(recycleView, adapter);
        setListener();
        initRefresh();
        xiding();
        setRecycleView();
        adapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else if (sp.getString("UserSjPhone", "").equals("") && (!sp.getString("SpareTwo", "").equals("1"))) {
                    toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                } else {
                    String itemId = list.get(position).getNum_iid() + "";
                    toDetail(itemId);
                }
            }
        });

    }
    private void setListener() {
        //RadioGroup的事件监听
        rgp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                for (int index = 0; index < rgp.getChildCount(); index++) {
                    RadioButton rb = (RadioButton) rgp.getChildAt(index);
                    if (rb.isChecked()) {
                        list.clear();
                        adapter.setDataList(list);
                        if (index == 0) {
                            sortType = "tk_total_sales_des";
                        } else if (index == 1) {
                            sortType = "tk_total_commi_des";
                        } else {
                            sortType = "total_sales_des";
                        }
                        RequestData();
                        break;
                    }
                }
            }
        });
    }


    public void RequestData() {
        if (!DeviceUtils.isNetworkAvalible(getActivity())) {
            ToastUtils.getInstance(getActivity()).showMessage("网络连接错误请检查");
        }
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetTBCateList(key, sortType, page, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "CateId" + key + "sort_type" + sortType + "Page" + page)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject obj) {
                if (obj.getString("code").equals("0")) {
                    SuperSearchBean bean = JSONObject.parseObject(obj.toString(), SuperSearchBean.class);
                    if ((null == bean.getData() || null == bean.getData().getTbk_dg_material_optional_response().getResult_list()) && page == 1) {
                        return;
                    } else if (null == bean.getData() || null == bean.getData().getTbk_dg_material_optional_response().getResult_list()) {
                        adapter.changeMoreStatus(adapter.NO_LOAD_MORE);
                        swipeRefreshLayout.setRefreshing(false);
                        return;
                    }
                    if (page == 1) {
                        list.clear();
                    }
                    list.addAll(bean.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data());
                    adapter.setDataList(list);
                    swipeRefreshLayout.setRefreshing(false);
                    if (list.size() % 30 != 0) {
                        isLoading = true;
                        adapter.changeMoreStatus(adapter.NO_LOAD_MORE);
                        return;
                    }
                    isLoading = false;
                    adapter.changeMoreStatus(adapter.LOADING_MORE);
                } else {
                    ToastUtils.getInstance(getActivity()).showMessage(obj.getString("message"));
                }
            }
        });
    }

    public void setRecycleView() {
        recycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                LinearLayoutManager linearManager = null;
                if (layoutManager instanceof LinearLayoutManager) {
                    linearManager = (LinearLayoutManager) layoutManager;
                }
                int lastVisibleItemPosition = linearManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    boolean isRefreshing = swipeRefreshLayout.isRefreshing();
                    if (isRefreshing) {
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        page++;
                        RequestData();
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    public void xiding() {
        appbar.addOnOffsetChangedListener(new AppBarStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (state == State.EXPANDED) {//展开状态
                    swipeRefreshLayout.setEnabled(true);
                } else if (state == State.COLLAPSED) {//折叠状态
                    swipeRefreshLayout.setEnabled(false);
                } else {//中间状态
                    swipeRefreshLayout.setEnabled(false);

                }
            }
        });
    }

    @Override
    public void initData() {
    }


    private void initRefresh() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                RequestData();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    public void toDetail(String itemId) {
        Bundle b = new Bundle();
        b.putSerializable("itemId", itemId);
        startActivity(TbProductDetailActivity.class, b);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(null!=list){
          list.clear();
          list=null;
        }
    }
}
